<template>
  <div class="app-container">
    <div class="page-pres-title">
      <span class="title-info">发货</span>
      <span class="title-line">|</span>
      <span class="title-info">{{ detailData.patientCode }}</span>
      <span class="title-line">|</span>
      <span class="title-info">{{ detailData.encounterId }}</span>
    </div>
    <el-collapse v-model="activeNames">
      <el-collapse-item title="就诊信息" name="encounterInfo">
        <div class="mod-details-wrap">
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-md">就诊号</div>
            <div class="item-info">{{ detailData.encounterId || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-sm">
            <div class="item-label item-label-md">医生</div>
            <div class="item-info">{{ detailData.doctorName || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-md">建立日期</div>
            <div class="item-info">{{ parseTime(detailData.diagnoseCreatedAt) || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">最后更新时间</div>
            <div v-bind:class="'item-info ' + renderTimeClass()">{{ parseTime(detailData.synTime) || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">最后审核时间</div>
            <div v-bind:class="'item-info ' + renderTimeClass()">{{ parseTime(detailData.auditorTime) || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">最后审核人</div>
            <div class="item-info">{{ detailData.auditorName || 'N/A' }}</div>
          </div>
        </div>
        <div class="mod-details-wrap">
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-md">开单诊所</div>
            <div class="item-info">{{ detailData.deptName || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-sm">
            <div class="item-label item-label-md">审核状态</div>
            <div v-bind:class="'item-info ' + renderStatusClass()">{{ handleAuditStatus(detailData.auditStatus) }}</div>
          </div>
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-md">是否配货</div>
            <div  v-bind:class="'item-info ' + renderStatusClass()">{{ handleIsEquip(detailData.isEquip) }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">是否发货</div>
            <div  v-bind:class="'item-info ' + renderStatusClass()">{{ handleIsSend(detailData.isSend) }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">是否结账</div>
            <div class="item-info">{{ handleIsBill(detailData.isBill) }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">是否需要审核</div>
            <div class="item-info">{{ handleIsAudit(detailData.isAudit) }}</div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item title="病案信息" name="patientInfo">
        <div class="mod-details-wrap">
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-md">病案号</div>
            <div class="item-info">{{ detailData.patientCode || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-sm">
            <div class="item-label item-label-md">顾客姓名</div>
            <div class="item-info">{{ detailData.patientName || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-md">性别</div>
            <div class="item-info">{{ handleGender(detailData.gender) || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">出生日期</div>
            <div class="item-info">{{ parseTime(detailData.dob) || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-xl">年龄/身高/体重</div>
            <div class="item-info">{{ detailData.age || 'N/A' }} / {{ detailData.height || 'N/A' }} / {{ detailData.weight || 'N/A' }}</div>
          </div>
        </div>
        <div class="mod-details-wrap">
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-lg">体温(摄氏度)</div>
            <div class="item-info">{{ detailData.temperature || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-sm">
            <div class="item-label item-label-md">血压BP</div>
            <div class="item-info">{{ detailData.bp || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-md">
            <div class="item-label item-label-lg">脉搏(bmp)</div>
            <div class="item-info">{{ detailData.bmp || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">呼吸</div>
            <div class="item-info">{{ detailData.breathe || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-xl">血氧饱和度</div>
            <div class="item-info">{{ detailData.bloodOxygen || 'N/A' }}</div>
          </div>
          <div class="mod-details-item mod-details-item-lg">
            <div class="item-label item-label-lg">末次月经</div>
            <div class="item-info">{{ detailData.lastMenstruation || 'N/A' }}</div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item title="过敏信息和其他注意事项" name="allergyInfo">
        <div class="mod-details-wrap">
          <div class="mod-details-item mod-details-item-col3">
            <div class="item-label item-label-md">药物过敏</div>
            <div class="item-info item-info-error">{{ detailData.drugAllergy }}</div>
          </div>
          <div class="mod-details-item mod-details-item-col3">
            <div class="item-label item-label-lg">食物过敏</div>
            <div class="item-info item-info-error">{{ detailData.foodAllergy }}</div>
          </div>
          <div class="mod-details-item mod-details-item-col3">
            <div class="item-label item-label-xl">非药物过敏</div>
            <div class="item-info item-info-error">{{ detailData.undrugAllergy }}</div>
          </div>
        </div>
        <div class="mod-details-wrap">
          <div class="mod-details-item">
            <div class="item-label item-label-md">警示</div>
            <div class="item-info item-info-error">{{ detailData.alertMark }}</div>
          </div>
        </div>
        <div class="mod-details-wrap">
          <div class="mod-details-item">
            <div class="item-label item-label-md">皮试结果</div>
            <div class="item-info item-info-error">{{ detailData.skinTest }}</div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item title="病例" name="medicalBg">
        <div class="mod-details-wrap">
          <div class="mod-details-item mod-details-item-col3">
            <div class="item-label item-label-md">主诉</div>
            <div class="item-info item-info-error">{{ detailData.subjective }}</div>
          </div>
          <div class="mod-details-item mod-details-item-col3">
            <div class="item-label item-label-lg">体格检查</div>
            <div class="item-info item-info-error">{{ detailData.assessment }}</div>
          </div>
          <div class="mod-details-item mod-details-item-col3">
            <div class="item-label item-label-xl">病史</div>
            <div class="item-info item-info-error">{{ detailData.medicalBg }}</div>
          </div>
        </div>
        <div class="mod-details-wrap">
          <div class="mod-details-item">
            <div class="item-label item-label-md">建议</div>
            <div class="item-info item-info-error">{{ detailData.plans }}</div>
          </div>
        </div>
        <div class="mod-details-wrap">
          <div class="mod-details-item">
            <div class="item-label item-label-md">备注</div>
            <div class="item-info item-info-error">{{ detailData.remarks }}</div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item title="商品及杂项明细" name="diagnoseDetail">
        <div class="diagnose-table-wrap">
          <div class="send-table-head-wrap">
            <div class="wrap-left">&nbsp;</div>
            <div class="wrap-right">
              <el-button
                type="primary"
                size="mini"
                :disabled="!isCanBackAndManualSend"
                @click="handleBackByManual()"
              >退货</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="handleSendByManual()"
                :disabled="!isCanBackAndManualSend"
              >手工发货</el-button>
            </div>
          </div>
          <el-table
            :data="diagnoseTableData"
            style="width: 100%"
          >
            <el-table-column label="商品编码" prop="materialId"  width="200" />
            <el-table-column label="名称" prop="materialName" class-name="font-primary-color font-primary-weight" />
            <el-table-column label="数量" prop="qty" class-name="font-primary-color" width="150">
              <template slot-scope="scope">
                <span :class="scope.row.qty >= 0 ? 'font-primary-color' : 'font-error-color'">{{ scope.row.qty }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="qtyUnitName" class-name="font-primary-color" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.qtyUnit }} {{ scope.row.qtyUnitName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="已发货数量" prop="totalSendQty" width="200">
              <template slot-scope="scope">
                <el-tag effect="dark" v-if="scope.row.color === 1" type="warning">{{ scope.row.totalSendQty }}</el-tag>
                <el-tag effect="dark" v-else-if="scope.row.color === 2" type="danger">{{ scope.row.totalSendQty }}</el-tag>
                <el-tag effect="dark" v-else>{{ scope.row.totalSendQty }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-collapse-item>
      <el-collapse-item title="发货明细" name="sendDetail">
        <div class="diagnose-table-wrap">
          <div class="send-table-head-wrap">
            <div class="wrap-left">
              <el-input
                v-model="scanBarcode"
                ref="scanDetailRef"
                placeholder="输入或扫描识别码"
                suffix-icon="el-icon-menu"
                size="small"
                @keyup.enter.native="getMaterial"
              />
            </div>
            <div class="wrap-right">
              <el-switch
                v-model="switchScanBack"
                active-text="扫码退回"
                style="margin-right: 20px;"
              ></el-switch>
              <el-button
                type="primary"
                size="mini"
                :disabled="!isCanSend"
                :loading="btnLoading.sendPills"
                @click="handleSendAndPrint()"
              >发货</el-button>
            </div>
          </div>
          <el-table
            :data="sendTableData"
            style="width: 100%"
          >
            <el-table-column label="物料编码" prop="materialId" width="200" />
            <el-table-column label="药名(Item)" prop="materialName" class-name="font-primary-color font-primary-weight" />
            <el-table-column label="发货数量" prop="sendQty" class-name="font-primary-color">
              <template slot-scope="scope">
                <div style="width: 150px;">
                  <el-input
                    :class="scope.row.leftSendQty < scope.row.sendQty ? 'send-input-error' : ''"
                    v-model="scope.row.sendQty"
                    size="small"
                    @input="handleSendChange(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="最后配药时间" prop="lastEquipTime" class-name="font-primary-color">
              <template slot-scope="scope">
                <div>{{ parseTime(scope.row.lastEquipTime) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="发货错误" prop="error" class-name="font-error-color" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleManualBack(scope.row)"
                >手工退回</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="font-color-primary">审核备注：{{ detailData.auditContent || '无' }}</div>
      </el-collapse-item>
    </el-collapse>
    <!-- 配药扫码错误提示 -->
    <el-dialog
      title="药品不在处方清单中"
      :visible.sync="dialogShow.scanBarCode"
      :show-close="false"
      width="30%"
      center
      @close="handleScanBarCodeDialogClose"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div>
        <el-input
          ref="scanCancelInput"
          v-model="scanCancleBarcode"
          placeholder="请扫码退出"
          suffix-icon="el-icon-menu"
          size="small"
          @keyup.enter.native="checkScanBarCode"
        />
      </div>
    </el-dialog>
    <!-- 扫码退回提示 -->
    <el-dialog
      title="配药退回"
      :visible.sync="dialogShow.scanBack"
      :show-close="false"
      width="60%"
      center
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-table
        :data="[currentScanItem]"
        style="width: 100%"
      >
        <el-table-column label="物料编码" prop="materialId" width="200" />
        <el-table-column label="药名(Item)" prop="materialName" class-name="font-primary-color font-primary-weight" />
        <el-table-column label="配货数量" prop="sendQty" class-name="font-primary-color" width="100"></el-table-column>
        <el-table-column label="退回数量" prop="scanNumPer" width="100">
          <template>
            <el-input
              v-model="backScanNumPer"
              @input="handleBackInputChange"
              size="small"
            />
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow.scanBack = false">取 消</el-button>
        <el-button type="primary" :disabled="backConfirmStatus" @click="dialogScanBackConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 扫码发药Dialog -->
    <el-dialog
      title="发货"
      :visible.sync="dialogShow.sendScan"
      :show-close="false"
      width="30%"
      center
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div style="margin-bottom: 15px;">
        <el-input
          v-model="sendPatientCode"
          ref="scanSendRef"
          placeholder="输入或扫描病案号"
          suffix-icon="el-icon-menu"
          size="small"
          @input="handleSendDialogChangeInput"
        />
      </div>
      <div>
        <el-select v-model="depotDefaultValue" placeholder="选择仓库" size="small" @change="handleSendDialogChangeSelect">
          <el-option
            v-for="item in depotList"
            :key="item.depotCode"
            :label="item.depotName"
            :value="item.depotCode">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleSendScanDialogClose">取 消</el-button>
        <el-button type="primary" :disabled="btnDisabled.sendPills" @click="handleSendPillsConfirm">发 货</el-button>
      </span>
    </el-dialog>
    <!-- 手工发药Dialog -->
    <el-dialog
      title="手工发药"
      :visible.sync="dialogShow.sendManual"
      :show-close="false"
      width="60%"
      center
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-table
        :data="currentManualData"
        style="width: 100%"
      >
        <el-table-column label="物料编码" prop="materialId" width="160" />
        <el-table-column label="药名(Item)" prop="materialName" class-name="font-primary-color font-primary-weight" />
        <el-table-column label="数量" prop="qty" class-name="font-primary-color" width="100">
          <template slot-scope="scope">
            <span :class="scope.row.qty >= 0 ? 'font-primary-color' : 'font-error-color'">{{ scope.row.qty }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="qtyUnitName" class-name="font-primary-color" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.qtyUnit }} {{ scope.row.qtyUnitName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已发货数量" prop="totalSendQty" width="100">
          <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.color === 1" type="warning">{{ scope.row.totalSendQty }}</el-tag>
            <el-tag effect="dark" v-else-if="scope.row.color === 2" type="danger">{{ scope.row.totalSendQty }}</el-tag>
            <el-tag effect="dark" v-else>{{ scope.row.totalSendQty }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发货数量" width="100">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.sendQty"
              size="small"
              @input="checkManualSendNum(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow.sendManual = false">取 消</el-button>
        <el-button type="primary" :disabled="btnDisabled.sendManual" @click="handleSendPillsManualConfirm()">确认发货</el-button>
      </span>
    </el-dialog>
    <!-- 手工退药Dialog -->
    <el-dialog
      title="退货"
      :visible.sync="dialogShow.backManual"
      :show-close="false"
      width="60%"
      center
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-table
        :data="currentBackManualData"
        style="width: 100%"
      >
        <el-table-column label="物料编码" prop="materialId" width="120" />
        <el-table-column label="药名(Item)" prop="materialName" class-name="font-primary-color font-primary-weight" />
        <el-table-column label="发货单号" prop="sendId" class-name="font-primary-color" />
        <el-table-column label="发货时间" prop="sendTime" class-name="font-primary-color" width="170">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.sendTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" prop="depotName" width="120" />
        <el-table-column label="已发货数量" prop="sendQty" width="100">
          <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.color === 1" type="warning">{{ scope.row.sendQty }}</el-tag>
            <el-tag effect="dark" v-else-if="scope.row.color === 2" type="danger">{{ scope.row.sendQty }}</el-tag>
            <el-tag effect="dark" v-else>{{ scope.row.sendQty }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="已退货数量" prop="totalReturnQty" class-name="font-primary-color" width="100" />
        <el-table-column label="退货数量" width="100">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.returnQty"
              size="small"
              @input="checkManualBackNum(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow.backManual = false">取 消</el-button>
        <el-button type="primary" :disabled="btnDisabled.backManual" @click="handleBackPillsManualConfirm()">确认退货</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getHead, auditHead } from "@/api/order/head"
import { diagnoseDetail, getMaterialList, getMaterialSendList } from "@/api/order/detail"
import { listSend, batchAdd, getDepotList, delivery } from "@/api/order/send"
import { getReturnList, returnBatchAdd } from "@/api/order/return"

export default {
  name: "Detail",
  data() {
    return {
      // Dialog展示对象
      dialogShow: {
        scanBarCode: false,
        scanBack: false,
        sendScan: false,
        sendManual: false,
        backManual: false
      },
      // 按钮禁用状态
      btnDisabled: {
        sendPills: true,
        sendManual: true,
        backManual: true
      },
      // 按钮loading状态
      btnLoading: {
        sendPills: false,
        saveAndPrint: false,
        backPills: false,
        sendManual: false
      },
      // sendId
      sendId: null,
      // 配药扫码的ID
      scanMaterialId: undefined,
      // 折叠面板默认展开的值
      activeNames: ['encounterInfo', 'patientInfo', 'diagnoseDetail', 'sendDetail'],
      // 扫描单据条形码
      scanBarcode: null,
      // 发药病案号条形码
      sendPatientCode: null,
      // 扫描错误单据的条形码
      scanCancleBarcode: null,
      // 每次退回的药品数量
      backScanNumPer: 0,
      // 扫码退回开关
      switchScanBack: false,
      // 是否能发药和配药
      isCanSend: false,
      // 是否能退药和手工发药
      isCanBackAndManualSend: false,
      // 当前扫描的配方明细
      currentScanItem: null,
      // 手工发药的明细列表
      currentManualData: null,
      // 手工退药明细列表
      currentBackManualData: null,
      // 处方列表数据
      diagnoseTableData: null,
      // 配药退回按钮状态
      backConfirmStatus: false,
      // 配发药列表明细
      sendTableData: [],
      // 仓库列表
      depotList: [],
      // 发药选择的仓库信息
      depotItem: null,
      // 仓库默认值
      depotDefaultValue: null,
      detailData: {
        encounterId: undefined,
        diagnoseId: undefined,
        diagnoseCreatedAt: undefined,
        deptCode: undefined,
        deptName: undefined,
        doctorCode: undefined,
        doctorName: undefined,
        patientCode: undefined,
        patientName: undefined,
        gender: undefined,
        dob: undefined,
        auditorId: undefined,
        auditorName: undefined,
        auditorTime: undefined,
        auditStatus: undefined,
        isAudit: undefined,
        auditContent: undefined,
        isEquip: undefined,
        isSend: undefined,
        isBill: undefined,
        age: undefined,
        height: undefined,
        weight: undefined,
        temperature: undefined,
        bp: undefined,
        bmp: undefined,
        breathe: undefined,
        bloodOxygen: undefined,
        lastMenstruation: undefined,
        drugAllergy: undefined,
        foodAllergy: undefined,
        undrugAllergy: undefined,
        alertMark: undefined,
        medicalBg: undefined,
        ext: undefined,
        diagnoseContent: undefined,
        isValid: undefined,
        synTime: undefined,
        skinTest: undefined,
        subjective: undefined,
        assessment: undefined,
        plans: undefined,
        remarks: undefined,
      },
      loading: false
    };
  },
  created() {
    this.getDetail();
  },
  methods: {
    getDetail() {
      const id = this.$route.params.id;
      this.loading = true;
      this.$nextTick(() => {
        this.$refs.scanDetailRef.focus()
      })

      getHead(id).then(response => {
        this.detailData = response.data;

        // 获取处方列表
        diagnoseDetail(this.detailData.diagnoseId).then(resp => {
          this.diagnoseTableData = resp.data;
          this.loading = false;
          this.isCanBackAndManualSend = resp.data.length > 0 ? true : false;
        })

        // 获取配发药列表
        listSend(this.detailData.diagnoseId).then(resp => {
          if(resp.data && resp.data.length > 0) {
            resp.data.forEach(item => {
              if(item.leftSendQty < item.sendQty) {
                this.isCanSend = false;
              } else {
                this.isCanSend = true;
              }
            })

            this.sendTableData = resp.data;
          }
          this.loading = false;
        })
      });
    },
    // 手工退回
    handleManualBack(row) {
      if(row.sendQty <= 0) {
        this.$message.error('配药数量不足，无法退回');
      } else {
        this.currentScanItem = row;
        this.dialogShow.scanBack = true;
      }
    },
    // 获取配发药列表
    getMaterial() {
      getMaterialList(this.detailData.diagnoseId, this.scanBarcode).then(resp => {
        this.backScanNumPer = resp.data.scanNumPer;

        if(this.sendTableData.length > 0) {
          for(let i = 0, len = this.sendTableData.length; i < len; i++) {
            let item = this.sendTableData[i];

            if(item.materialId === resp.data.materialId) {
              if(this.switchScanBack) {
                if(item.sendQty <= 0) {
                  this.$message.error('配药数量不足，无法退回');
                } else {
                  this.currentScanItem = item;
                  this.dialogShow.scanBack = true;
                }
              } else {
                item.sendQty = parseInt(item.sendQty) ? parseInt(item.sendQty) + resp.data.scanNumPer : resp.data.scanNumPer;
                this.handleSendChange(item);
              }

              break;
            }

            if(i === len - 1) {
              resp.data.sendQty = parseInt(resp.data.sendQty) + resp.data.scanNumPer;
              this.sendTableData.push(resp.data);
            }
          }
        } else {
          resp.data.sendQty += resp.data.scanNumPer;
          this.sendTableData.push(resp.data);
          this.handleSendChange(resp.data);
          // 检查是否有超出库存的配方
          // if(resp.data.leftSendQty < resp.data.sendQty) {
          //   this.isCanSend = false;
          // } else {
          //   this.isCanSend = true;
          // }
        }

        this.scanBarcode = '';
      }).catch(error => {
        this.dialogShow.scanBarCode = true;

        // 异步处理获取焦点的问题
        this.$nextTick(() => {
          this.$refs.scanCancelInput.focus()
        })
      })
    },
    // 扫码错误后，对比弹框中扫的码是不是和之前的一样
    checkScanBarCode(e) {
      if(this.scanCancleBarcode === this.scanBarcode) {
        this.dialogShow.scanBarCode = false;
        this.scanCancleBarcode = '';
        this.scanBarcode = '';
      } else {
        this.$message.error('扫码不一致，请扫描当前需要退回的货物条码/二维码');
      }
    },
    // 检查手工发药数量
    checkManualSendNum() {
      for(let i = 0, len = this.currentManualData.length; i < len; i++) {
        const item = this.currentManualData[i];

        if(item.sendQty !== '' && !/^((\d+)|(-\d+)|(0+))$/.test(parseInt(item.sendQty), 10)) {
          this.btnDisabled.sendManual = true;
          this.$message.error('发货数量必须为整数');
          return false;
        }

        if(parseInt(item.sendQty, 10) > parseInt(item.qty, 10) ) {
          this.btnDisabled.sendManual = true;
          this.$message.error('处方数量不足');
          return false;
        }

        this.btnDisabled.sendManual = false;
      }
    },
    // 检查手工退药数量
    checkManualBackNum() {
      for(let i = 0, len = this.currentBackManualData.length; i < len; i++) {
        const {returnQty, sendQty, totalReturnQty} = this.currentBackManualData[i];

        if(returnQty !== '' && !/^((\d+)|(0+))$/.test(parseInt(returnQty, 10))) {
          this.btnDisabled.backManual = true;
          this.$message.error('退货数量必须为整数');
          return false;
        }

        if(parseInt(returnQty, 10) > (parseInt(sendQty, 10) - parseInt(totalReturnQty, 10))) {
          this.btnDisabled.backManual = true;
          this.$message.error('不可以超退');
          return false;
        }

        this.btnDisabled.backManual = false;
      }
    },
    // 渲染时间是否标红
    renderTimeClass() {
      if (new Date(this.detailData.auditorTime) <= new Date(this.detailData.synTime)) {
        return 'font-error-color';
      }

      return '';
    },
    // 渲染是否配药，是否发药标红
    renderStatusClass() {
      const {isEquip, isSend, auditStatus} = this.detailData;

      if(auditStatus !== 1 && isSend !== 0) {
        return 'font-error-color';
      }

      if(auditStatus !== 1 && isEquip !== 0) {
        return 'font-error-color';
      }

      if(auditStatus === 3) {
        return 'font-error-color';
      }

      return '';
    },
    // 扫码错误弹层关闭回调
    handleScanBarCodeDialogClose() {
      // 异步处理获取焦点的问题
      this.$nextTick(() => {
        this.$refs.scanDetailRef.focus()
      })
    },
    // 保存并打印
    handleSaveAndPrint() {
      batchAdd(this.sendTableData).then(resp => {
        this.$message.success('保存配药单成功');
      })
    },
    // 发货
    handleSendAndPrint() {
      this.btnLoading.sendPills = true;

      batchAdd(this.sendTableData).then(resp => {
        this.btnLoading.sendPills = false;
        // 执行发药逻辑
        this.sendId = resp.data;
        this.sendTableData = this.sendTableData.map(item => {
          item.sendId = resp.data
          return item
        })
        this.handleSendByScan(resp.data);
      }).catch(error => {
        this.btnLoading.sendPills = false;
        this.$message.error('发货失败，请稍后重试');
      })
    },
    // 确认发药按钮事件
    handleSendPillsManualConfirm() {
      batchAdd(this.currentManualData).then(resp => {
        // 执行发药逻辑
        this.sendId = resp.data;
        this.handleSendByScan(resp.data);
        this.dialogShow.sendManual = false;
      })
    },
    // 确认退药按钮事件
    handleBackPillsManualConfirm() {
      const dataArr = this.currentBackManualData.map(item => {
        const { diagnoseId, sendId, sendItemNo, materialId, materialName, barcode, returnQty } = item;

        return {
          diagnoseId,
          sendId,
          sendItemNo: item.itemNo,
          materialId,
          materialName,
          barcode,
          returnQty: parseInt(returnQty, 10)
        }
      });

      returnBatchAdd(dataArr).then(resp => {
        this.dialogShow.backManual = false;

        this.$message({
          message: '退药成功',
          type: 'success',
          duration: 2000,
          onClose: () => {
            // this.$router.push(`/order/head`);
            window.location.reload();
          }
        })
      })
    },
    // 扫码发药
    handleSendByScan(sendId) {
      getDepotList(sendId).then(resp => {
        this.depotList = resp.data;
        // 默认选择数组中第一个
        this.depotDefaultValue = resp.data[0].depotName
        this.depotItem = resp.data[0]
        this.dialogShow.sendScan = true

        // 异步处理获取焦点的问题
        this.$nextTick(() => {
          this.$refs.scanSendRef.focus()
        })
      })
    },
    handleSendScanDialogClose() {
      this.sendPatientCode = ''
      this.dialogShow.sendScan = false

      // 异步处理获取焦点的问题
      this.$nextTick(() => {
        this.$refs.scanDetailRef.focus()
      })
    },
    // 手工发药
    handleSendByManual() {
      getMaterialSendList(this.detailData.diagnoseId).then(resp => {
        this.currentManualData = resp.data;
        this.dialogShow.sendManual = true;
        this.checkManualSendNum();
      })
    },
    // 手工退药
    handleBackByManual() {
      getReturnList(this.detailData.diagnoseId).then(resp => {
        this.currentBackManualData = resp.data;
        this.dialogShow.backManual = true;
        this.checkManualBackNum();
      })
    },
    // 处理结账信息
    handleIsBill(isBill) {
      let str = 'N/A';

      switch(isBill) {
        case 0:
          str = '否';
        break;
        case 1:
          str = '是';
        break;
        default:
          str = 'N/A';
      }

      return str;
    },
    // 处理是否发药
    handleIsSend(isSend) {
      let str = 'N/A';

      switch(isSend) {
        case 0:
          str = '否';
        break;
        case 1:
          str = '是';
        break;
        case 2:
          str = '部分发';
        break;
        case 3:
          str = '超发';
        break;
        default:
          str = 'N/A';
      }

      return str;
    },
    // 处理是否配药
    handleIsEquip(isEquip) {
      let str = 'N/A';

      switch(isEquip) {
        case 0:
          str = '否';
        break;
        case 1:
          str = '是';
        break;
        case 2:
          str = '部分配';
        break;
        case 3:
          str = '超配';
        break;
        default:
          str = 'N/A';
      }

      return str;
    },
    // 处理审核状态
    handleAuditStatus(auditStatus) {
      let str = 'N/A';

      switch(auditStatus) {
        case 0:
          str = '未审核';
        break;
        case 1:
          str = '审核通过';
        break;
        case 2:
          str = '审核未通过';
        break;
        case 3:
          str = '重新审核';
        break;
        case 4:
          str = '无需审核';
        break;
        default:
          str = 'N/A';
      }

      return str;
    },
    // 处理是否需要审核
    handleIsAudit(isAudit) {
      let str = 'N/A';

      switch(isAudit) {
        case 0:
          str = '否';
        break;
        case 1:
          str = '是';
        break;
        default:
          str = 'N/A';
      }

      return str;
    },
    // 处理性别
    handleGender(gender) {
      let str = 'N/A';

      switch(gender) {
        case 1:
          str = '男';
        break;
        case 2:
          str = '女';
        break;
        case 3:
          str = '未知';
        break;
        default:
          str = 'N/A';
      }

      return str;
    },
    // 处理配发药明细配药数量变化
    handleSendChange(row) {
      const { sendQty, leftSendQty } = row;

      if(sendQty > leftSendQty) {
        row.error = '配药数量超过处方量'
        this.isCanSend = false;
      } else {
        row.error = ''
        this.isCanSend = true;
      }
    },
    // 扫码 && 手工退回确认按钮
    dialogScanBackConfirm() {
      this.currentScanItem.sendQty -= this.backScanNumPer;
      // 检查是否有超出库存的配方
      if(this.currentScanItem.leftSendQty < this.currentScanItem.sendQty || this.currentScanItem.sendQty <= 0) {
        this.isCanSend = false;
      }
      this.handleSendChange(this.currentScanItem);
      this.dialogShow.scanBack = false;
    },
    // 扫码 && 手工退回输入框input事件
    handleBackInputChange(e) {
      if(e > this.currentScanItem.sendQty) {
        this.backConfirmStatus = true;
      } else {
        this.backConfirmStatus = false;
      }
    },
    // 发药按钮事件
    handleSendPillsConfirm() {
      if(this.sendPatientCode.toLocaleLowerCase() === this.detailData.patientCode.toLocaleLowerCase()) {
        delivery(this.sendId, {
          sendId: this.sendId,
          patientCode: this.detailData.patientCode,
          depotCode: this.depotItem.depotCode,
          depotName: this.depotItem.depotName
        }).then(resp => {
          this.$message.success('发货成功');
          this.dialogShow.sendScan = false;
          setTimeout(() => {
            window.location.reload();
          }, 2000);
        })
      } else {
        this.$message.error('客户信息和处方不匹配');
      }
    },
    handleSendDialogChangeInput() {
      if(this.depotDefaultValue && this.sendPatientCode) {
        this.btnDisabled.sendPills = false;
      }
    },

    // 发药input和select change事件
    handleSendDialogChangeSelect(e) {
      if(this.depotDefaultValue && this.sendPatientCode) {
        this.btnDisabled.sendPills = false;

        let depotItem = this.depotList.find(item => {
            return item.depotCode === e;
        })

        this.depotItem = depotItem;
      }
    },
  }
};
</script>

<style lang="scss" scoped>
  .page-pres-title {
    margin-bottom: 15px;
    font-size: 13px;
    color: #3e7e90;
    .title-line {
      margin-left: 5px;
      margin-right: 5px;
    }
  }
  .mod-details-wrap {
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
    .mod-details-item {
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .mod-details-item {
    overflow: hidden;
    display: inline-block;
    vertical-align: top;
    &.mod-details-item-sm {
      width: 150px;
    }
    &.mod-details-item-md {
      width: 200px;
    }
    &.mod-details-item-lg {
      width: 265px;
    }
    &.mod-details-item-col3 {
      width: 30%;
    }
    .item-label {
      float: left;
      font-size: 12px;
      color: #333;
      font-weight: bold;
      &.item-label-lg {
        width: 85px;
      }
      &.item-label-md {
        width: 60px;
      }
      &.item-label-xl {
        width: 95px;
      }
      &.item-label-5 {
        width: 80px;
      }
    }
    .item-info {
      overflow: hidden;
      font-size: 12px;
      color: #0018a1;
      line-height: 22px;
      &.item-info-error {
        font-weight: bold;
        color: #eb2323;
      }
    }
  }
  .diagnose-extend-item {
    overflow: hidden;
    margin-top: 5px;
    &:first-child {
      margin-top: 0;
    }
    .item-label {
      float: left;
      font-size: 14px;
      font-weight: bold;
      margin-right: 10px;
      color: #333;
    }
    .item-info {
      overflow: hidden;
      font-size: 14px;
      color: #0018a1;
    }
  }
  .diagnose-table-wrap {
    margin-bottom: 25px;
  }
  .send-table-head-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    .wrap-left {
      width: 400px;
    }
  }
  .font-bg {
    display: inline-block;
    width: 50px;
    height: 100%;
    text-align: center;
  }
  .font-warning-color {
    .font-bg {
      background-color: #fdefb6;
    }
  }
  .font-error-color {
    .font-bg {
      background-color: #ed6e6a;
    }
  }
  .font-primary-color {
    .font-bg {
      background-color: transparent;
    }
  }
</style>

<style>
  .el-table td.font-error-color .cell {
    color: #eb2323;
  }
  .send-input-error .el-input__inner {
    border: 1px solid #ed6e6a!important;
    color: #ed6e6e!important;
  }
  .el-table td.font-primary-color .cell {
    color: #0018a1;
  }
  .el-table td.font-primary-weight .cell {
    font-weight: bold;
  }
  .font-color-primary {
    color: #0018a1;
  }
</style>
